/*
============================================================================
 Name        : Connection.h
 Author      : 
 Version     :
 Copyright   : Your copyright notice
 Description : CConnection declaration
============================================================================
*/

#ifndef __CONNECTION_H__
#define __CONNECTION_H__

#include <e32base.h>
#include <e32std.h>
#include <es_sock.h>
#include <in_sock.h>

class MConnectionObserver
{
public:
	virtual void ResponseRequestedL(TDesC8& aResponse) = 0;
	virtual void StreamingRequestedL(TDesC8& aChunk) = 0;
	virtual void StreamingEndedL() = 0;
	virtual void ResponseErrorL(TInt aError) = 0;
};

class CConnection : public CActive
{
public: //constructor and destructors
	IMPORT_C static CConnection* Static();
	IMPORT_C static void Destroy();


private: //constructor
	~CConnection();
	CConnection();
	void ConstructL();
	

public: // New functions
	IMPORT_C void SetObserver(MConnectionObserver* aObserver);
	IMPORT_C void RequestL(const TDesC& aUrl);
	IMPORT_C void StreamingRequestL(const TDesC& aUrl);
	IMPORT_C void StreamingRequestL(const TDesC& aUrl, const TDesC8& aAdditionalHeaders);

public: //new functions
	void Pause();
	void Resume();


private: //new functions
	void ResolveL();
	void ConnectL();
	void SendRequestL();
	void ReceiveL();
	void NotifyReceivedDataL();
	void SetRequestStatus(TInt aStatus);
	void FinishedL();
	void CloseAndClean();

	void BuildRequestL(const TDesC& aUrl, const TDesC8& aAdditionalHeaders);
	void ManageHttpResponseL();
	void SearchForLastChunk();


private: // From CActive
	// Handle completion
	void RunL();
	
	// How to cancel me
	void DoCancel();
	
	// Override to handle leaves from RunL(). Default implementation causes
	// the active scheduler to panic.
	TInt RunError(TInt aError);

private: //new functions


private:
	//State of active object
	enum EState
	{
		ENotConnected,
		EResolving,
		EConnecting,
		ESending,
		EReceiving,
		ENotifyingReceived,
		EPaused,
		EFinished,
		EFailed
	} iState;

private: //data
	//Observer
	MConnectionObserver* iObserver;

	//Socket connection
	RSocketServ iSocketServ;
	RSocket iSocket;

	//Connection parameters
	TSockXfrLength iResponseChunkSizePkg;
	RHostResolver iHostResolver;
	TNameEntry iHostAddress;
	TInetAddr iAddress;
	TBuf<256> iServerName;
	TUint iPort;

	//Request parameters
	HBufC *iUrl;
	HBufC8 *iRequest;

	//Response buffer
	TUint8* iStreamingBuffer;
	TPtr8 iStreamingBufferPtr;

	//Http response
	HBufC8* iResponse;

	//Mark if we use streaming or not
	TBool iStreamingRequest;

};

#endif //__CONNECTION_H__


